//
//  MoreViewController.m
//  FNer
//
//  Created by 王展 on 15/10/9.
//  Copyright (c) 2015年 wangzhan. All rights reserved.
//

#import "MoreViewController.h"
#import "BaseCollectionView.h"
#import "MoreCollectionViewCell.h"
#import "AFNetworking.h"
#import "CommunityDetailViewController.h"
#import "Channels.h"
#import "MJRefresh.h"

@interface MoreViewController ()

@property(nonatomic,retain)BaseCollectionView *moreCV;
@property(nonatomic,retain)NSMutableArray *channelsArray;
@property(nonatomic,retain)UILabel *titleLabel;

@end

@implementation MoreViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.text = self.atheme.themeName;
    self.titleLabel.font = [UIFont systemFontOfSize:18 * XWIDTH];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = self.titleLabel;
    
    NSString *string = [[NSUserDefaults standardUserDefaults] objectForKey:@"nighting"];
    if ([string isEqualToString:@"yes"]) {
#warning 改的颜色
        self.titleLabel.textColor = [UIColor blackColor];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeColoring:) name:@"changeColoring" object:nil];
    
    
    //左侧按钮
    UIImage *leftImage = [UIImage imageNamed:@"导航栏_button_back_用于白和灰.png"];
    leftImage = [leftImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:leftImage style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonAction)];
    //创建更多页面
    [self createMoreView];
    //获取更多页面数据
    [self addHeaderRefresh];
    
}
//下拉刷新
-(void)addHeaderRefresh
{
    
    self.moreCV.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
         [self getMoreData];
    }];
    [self.moreCV.header beginRefreshing];

    
    
}
//点击左侧按钮触发
-(void)leftButtonAction
{
    [self.navigationController popToRootViewControllerAnimated:NO];
}
//创建更多页面
-(void)createMoreView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(WIDTH - 20 * XWIDTH, 100 * XHIGHT);
    flowLayout.sectionInset = UIEdgeInsetsMake(10 * XHIGHT, 10 * XWIDTH, 10 * XHIGHT, 10 * XWIDTH);
    flowLayout.minimumLineSpacing = 1;
    
    self.moreCV = [[BaseCollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HIGHT - 64) collectionViewLayout:flowLayout];
    self.moreCV.delegate = self;
    self.moreCV.dataSource = self;
    [self.view addSubview:self.moreCV];
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.channelsArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self.moreCV registerClass:[MoreCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    MoreCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    
    cell.backgroundColor = [UIColor whiteColor];
    cell.achannel = [self.channelsArray objectAtIndex:indexPath.row];
    
    return cell;
}
//获取更多页面数据
-(void)getMoreData
{
    
    
    
    
    
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    long long int date = (long long int)time;
    NSString * timeStr = [NSString stringWithFormat:@"%lld",date];
    NSString *url_str = [NSString stringWithFormat:@"http://api.imzhitu.com/operations/channel_queryThemeChannel"];
    NSString *themeid = [NSString stringWithFormat:@"%ld",self.achannel.id];
    NSDictionary *body = @{@"themeId":themeid, @"maxId":@"0",@"start":@"1",@"limit":@"20"};
    
    
    
    AFNetworkReachabilityManager *Netmanger = [AFNetworkReachabilityManager sharedManager];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    NSString *cookieStr = [NSString stringWithFormat:@"IMZHITU_REMEMBER_ME_COOKIE=dXp6ZzFQV29DTTBXSHVpdUE5STFyZz09Oko3Mk5OcTZxTTJYQ1BiMHVpd2hwdHc9PQ; JSESSIONID=3E3A742551270F4A58D107283C95ABE7; SERVERID=522aae22aff9f62a7356b879a9eb14e6|%@|1444396100",timeStr];
    
    [manager.requestSerializer setValue:cookieStr forHTTPHeaderField:@"Cookie"];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager POST:url_str parameters:body success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
        [Netmanger stopMonitoring];
        self.channelsArray = [NSMutableArray array];
        NSMutableDictionary *bigDic = responseObject;
        NSMutableArray *channelArray = [bigDic objectForKey:@"channels"];
        for (NSMutableDictionary *dic in channelArray) {
            Channels *achannel = [[Channels alloc] init];
            [achannel setValuesForKeysWithDictionary:dic];
            [self.channelsArray addObject:achannel];
        }
        [self.moreCV.header endRefreshing];
        [self.moreCV reloadData];

    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
        NSLog(@"没有网络");
        [self.moreCV.header endRefreshing];

    }];
}
//点击cell触发事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    CommunityDetailViewController *communityDetailVC = [[CommunityDetailViewController alloc] init];
    [self.navigationController pushViewController:communityDetailVC animated:NO];
    communityDetailVC.achannel = [self.channelsArray objectAtIndex:indexPath.row];
}

-(void)changeColoring:(NSNotification *)notification
{
#warning 改的颜色
    self.titleLabel.textColor = [UIColor blackColor];
    
    NSString *string = [notification object];
    if ([string isEqualToString:@"no"]) {
        
#warning 原有颜色
        self.titleLabel.textColor = [UIColor whiteColor];
    }
    //保存当前状态值
    [[NSUserDefaults standardUserDefaults] setObject:string forKey:@"nighting"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
